package com.cll.prototype.common.util;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 描述信息:
 * 生成随机数工具类
 * @author CLL
 * @version 1.0
 * @date 2020/10/28 21:39
 */
public class RandomUtils {

    private static final ReentrantLock REENTRANT_LOCK = new ReentrantLock();

    /**
     * 去除中间的横线,生成UUID的随机字符串
     * @return  UUID字符串
     */
    public static String getUUID(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }

    /**
     * 生成随机
     * 100万次耗时200ms
     * @param length    随机字符串长度
     * @return  随机字符串
     */
    public static String getRandomStr1(int length){
        REENTRANT_LOCK.lock();
        try {
            StringBuilder result = new StringBuilder();
            Random random = new Random();
            for (int i = 0; i < length; i++) {
                result.append(random.nextInt(10));
            }
            return result.toString();
        } finally {
            REENTRANT_LOCK.unlock();
        }
    }

    /**
     * 生成随机
     * 100万次耗时131ms
     * @param length    随机字符串长度
     * @return  随机字符串
     */
    public static String getRandomStr2(int length){
        REENTRANT_LOCK.lock();
        try {
            Random random = new Random();
            int min = 1;
            for (int i = 0; i < (length - 1); i++) {
                min *= 10;
            }
            int max = (min * 10) - 1;
            return random.nextInt(max - min) + min + "";
        } finally {
            REENTRANT_LOCK.unlock();
        }
    }
}